package com.powernode.ssm.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil; 
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.ssm.dao.*;
import com.powernode.ssm.pojo.vo.*;
import com.powernode.ssm.pojo.po.*;
import com.powernode.ssm.pojo.bo.*;
import com.powernode.ssm.service.*;
import com.powernode.ssm.utils.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

@Slf4j
@Service
public class EmpServiceImpl extends ServiceImpl<EmpDao, EmpPo> implements EmpService {

   @Autowired
   EmpDao empDao;

   @Autowired
   private SpringUtils springUtils;

   @Value("${export.template_path}")
   private String tempPath;

   @Value("${export.exportPath}")
   private String exportPath; 

   @Value("${export.dsp}")
   private boolean encrypt;

   @Override
   public ResponseUtils queryEmp (QueryEmpVo queryEmpVo) {

       int current = queryEmpVo.getCurrentPage();
       int size = queryEmpVo.getPageSize();

        Page<EmpPo> page = empDao.queryEmp(
               new Page<>(current, size),queryEmpVo);

        PageBo pageBo = PageBo.builder()
               .current(current)
               .size(size)
               .total(page.getTotal())
               .dataList(page.getRecords())
               .build();

       return new ResponseUtils<>(ReturnCodeEnum.SUCCESS.getCode(),ReturnCodeEnum.SUCCESS.getMsg(),pageBo);
   }

   @Override
   public ResponseUtils updateEmp (UpdateEmpVo updateEmpVo) {

       String id = updateEmpVo.getEmpno();
       int num = empDao.countEmp(id);
       if (num==0){
           return new ResponseUtils<>(ReturnCodeEnum.APPINFO_NOT_FOUND.getCode(), ReturnCodeEnum.APPINFO_NOT_FOUND.getMsg(),null);
       }
       empDao.updateEmp(updateEmpVo);

       springUtils.saveLog("更新员工信息");
       return new ResponseUtils<>(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMsg(),null);
   }

   @Override
   public ResponseUtils saveEmp (SaveEmpVo saveEmpVo) {

       String id = saveEmpVo.getEmpno();
       int num = empDao.countEmp(id);
       if (num>0){
           return new ResponseUtils<>(ReturnCodeEnum.SAME_RECORD_ERR.getCode(), ReturnCodeEnum.SAME_RECORD_ERR.getMsg(), null);
       }
       empDao.insertEmp(saveEmpVo);

       springUtils.saveLog("增加员工信息");
       return new ResponseUtils<>(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMsg(), null);
   }

   @Override
   public ResponseUtils batchDeleteEmp(DeleteEmpVo deleteEmpVo) {

       empDao.deleteEmp(deleteEmpVo);

       springUtils.saveLog("删除员工信息");
       return new ResponseUtils<>(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMsg(), null);
   }

   @Override
   public ResponseUtils exportEasyExcelWithTemplate(HttpServletResponse httpServletResponse, H5UserinfoPo h5UserinfoPo, QueryEmpVo item) {

       int current = item.getCurrentPage();
       int size = item.getPageSize();
       String tempPathFileName ="员工导出模版";//需要修改
       String exportPathFileName = "exportEmp";//需要修改
       String suffix = ".xlsx";//后缀名

       List<EmpPo> data = empDao.queryEmp(
               new Page<>(current, size), item).getRecords();

       ArrayList<ExportEmpBo> bos =new ArrayList<>();
       if (ArrayUtil.isNotEmpty(data)){
           data.forEach(item1 -> {
               ExportEmpBo bo = BeanUtil.copyProperties(item1, ExportEmpBo.class);
               bos.add(bo);
           });
       }

       File file = FileUtil.file(exportPath);
       file.mkdirs();
       //导出excel到指定服务器目录
       String excelPath = ImportAndExportUtils.exportEasyExcelWithTemplate(
               tempPath + File.separator + tempPathFileName + suffix,
               exportPath + File.separator + exportPathFileName + suffix,
               bos);

       //读取导出到指定服务器目录的excel返回输出流给前端
       ImportAndExportUtils.export(httpServletResponse, h5UserinfoPo,encrypt,
               excelPath.substring(0,excelPath.lastIndexOf(".")), suffix);

       springUtils.saveLog("导出员工信息");
       return null;
   }

   @Override
   public ResponseUtils importEasyExcelWithTemplate(ImportEmpVo importEmpVo, H5UserinfoPo h5UserinfoPo) {
        InputStream inputStream = null;
        String msg = "";
        try {
             inputStream = importEmpVo.getFile().getInputStream();
             EmpListener empListener = new EmpListener(empDao, h5UserinfoPo);
             //第二个实体类参数需要加上@ExcelProperty(index = 0,value = "xxx")注解
             EasyExcel.read(inputStream, ImportEmpBo.class,empListener).sheet(0).doRead();
             msg = empListener.getMsg();
        }catch (NoSuchBeanDefinitionException e){
           e.printStackTrace();
           return new ResponseUtils<>(ReturnCodeEnum.IMPORT_FIELD_EMPTY_ERR.getCode(), 
            ReturnCodeEnum.IMPORT_FIELD_EMPTY_ERR.getMsg(), null);
        }catch (NoSuchElementException e){
           e.printStackTrace();
           return new ResponseUtils<>(ReturnCodeEnum.IMPORT_FORMAT_OR_EMPTY_ERR.getCode(),
                   ReturnCodeEnum.IMPORT_FORMAT_OR_EMPTY_ERR.getMsg(), null);
        }catch (Exception e) {
           e.printStackTrace();
           return new ResponseUtils<>(ReturnCodeEnum.IMPORT_FILE_ERR.getCode(), ReturnCodeEnum.IMPORT_FILE_ERR.getMsg(), null);
        }
        finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        springUtils.saveLog("导入员工信息");
        return new ResponseUtils<>(ReturnCodeEnum.SUCCESS.getCode(), msg, null);
    }

}
